//
//  CommonRequestApi.m
//  NewProject
//
//  Created by Xu小波 on 2017/11/29.
//  Copyright © 2017年 FZ. All rights reserved.
//

#import "CommonRequestApi.h"
#import "YTKNetworkConfig.h"
#import "YTKNetworkAgent.h"

#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>

#define kPublicKEY @"sj3iUJ1C3lt74qe9LANPmILlsUT4UyX3In7YNRbujlI"

@interface CommonRequestApi ()

@property (nonatomic, copy) NSString *URL;

@property (nonatomic, strong) id requestBody;

@property (nonatomic, strong) id requestHeader;

@property (nonatomic, assign) YTKRequestMethod lxRequestMethod;

@property (nonatomic, assign) NSTimeInterval lxRequestTimeoutInterval;

@end

@implementation CommonRequestApi

#pragma mark - public

- (CommonRequestApi *(^)(NSString *))lxRequestURL {
    return ^(NSString *requestURL){
        self.URL = requestURL;
        return self;
    };
}

- (CommonRequestApi *(^)(YTKRequestMethod))lxMethod {
    return ^(YTKRequestMethod method){
        self.lxRequestMethod = method;
        return self;
    };
}

- (CommonRequestApi *(^)(id))lxHeader {
    return ^(id header) {
        self.requestHeader = header;
        return self;
    };
}

- (CommonRequestApi *(^)(id))lxBody {
    return ^(id body) {
        self.requestBody = body;
        return self;
    };
}

- (CommonRequestApi *(^)(NSTimeInterval))lxTimeoutInterval {
    return ^(NSTimeInterval timeout) {
        self.lxRequestTimeoutInterval = timeout;
        return self;
    };
}

#pragma mark - private

- (BOOL)useCDN {
    return YES;
}

//请求url
- (NSString *)requestUrl {
    return self.URL;
}

//请求方式
- (YTKRequestMethod)requestMethod {
    
    if (!_lxRequestMethod) {
        return YTKRequestMethodPOST;
    }
    
    return self.lxRequestMethod;
}

- (YTKRequestSerializerType)requestSerializerType {
    return YTKRequestSerializerTypeJSON;
}

//请求头
- (NSDictionary *)requestHeaderFieldValueDictionary {
    
    NSMutableDictionary *headerDic_m = [NSMutableDictionary dictionary];
    
    if ([self.requestHeader isKindOfClass:[NSDictionary class]]) {
        
        [headerDic_m setValuesForKeysWithDictionary:self.requestHeader];
        
    }else if ([self.requestHeader isKindOfClass:[NSString class]]){
        
        NSString *jsonString = self.requestHeader;
        NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error = nil;
        NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
        if (!error) {
            
            [headerDic_m setValuesForKeysWithDictionary:dic];
        }else{
            
            NSLog(@"请求地址:%@，请求头转换出错:%@", self.URL, error);
        }
    }
    [headerDic_m setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"kUserId"] forKey:@"userId"];
    
    [headerDic_m setValue:[self stringFromDate] forKey:@"timestamp"];//上传时间戳
    
    [headerDic_m setValue:@"" forKey:@"equipmentInfo"];//设备信息
    
    NSData *dataHeaderOne = [NSJSONSerialization dataWithJSONObject:headerDic_m options:0 error:nil];// options:0 写成NSJSONWritingPrettyPrinted会出错，livesxu
    NSString *dataHeaderOne_string=[[NSString alloc]initWithData:dataHeaderOne encoding:NSUTF8StringEncoding];
    
    NSString *signString = [self hmac:dataHeaderOne_string withKey:kPublicKEY];
    
    NSDictionary *headerTotal = [NSDictionary dictionaryWithObjectsAndKeys:signString, @"sign",dataHeaderOne_string, @"identification",@"application/json", @"content-type", nil];
    
    return headerTotal;
}

//请求参数
- (id)requestArgument {
    
    if ([self.requestBody isKindOfClass:[NSDictionary class]]) {
        return self.requestBody;
    }
    
    if (![self.requestBody isKindOfClass:[NSString class]]) {
        return nil;
    }
    
    if (![self.requestBody isValid]) {
        return nil;
    }
    
    NSString *jsonString = self.requestBody;
    NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
    if (error) {
        NSLog(@"请求地址:%@，请求参数转换出错:%@", self.URL, error);
        return nil;
    }
    return dic;
}

- (NSTimeInterval)requestTimeoutInterval {
    if (self.lxRequestTimeoutInterval > 0) {
        return self.lxRequestTimeoutInterval;
    }
    return 15.0f;
}

//- (void)startWithCompletionBlockWithSuccess:(YTKRequestCompletionBlock)success failure:(YTKRequestCompletionBlock)failure {
//    
//    [super startWithCompletionBlockWithSuccess:success failure:failure];
//}

- (NSString *)stringFromDate{
    
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970] *1000;
    
    return [NSString stringWithFormat:@"%.0f",time];
}

/**
 *  加密方式,MAC算法: HmacSHA256
 *
 *  @param plaintext 要加密的文本
 *  @param key       秘钥
 *
 *  @return 加密后的字符串
 */
- (NSString *)hmac:(NSString *)plaintext withKey:(NSString *)key
{
    const char *cKey  = [key cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cData = [plaintext cStringUsingEncoding:NSUTF8StringEncoding];
    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)];
    const unsigned char *buffer = (const unsigned char *)[HMACData bytes];
    NSMutableString *HMAC = [NSMutableString stringWithCapacity:HMACData.length * 2];
    for (int i = 0; i < HMACData.length; ++i){
        [HMAC appendFormat:@"%02x", buffer[i]];
    }
    
    return HMAC;
}

@end
